
 // life.cpp
 // rectrates Conway's "Game of Life"
 #include <conio.h>

 const unsigned char top = '\xDF' ;
 const unsigned char bot = '\xDC' ;
 const unsigned char both = '\xDB' ;
 const int maxCols = 80 ;
 const int maxRows = 25 ;
 const int maxRealRows = 25 ;

 enum state { dead, alive } ;

 class Cell
  {
    private :
       int xCo , yCo ;
       state oldState , newState ;
    public :
       void InitCell (int,int) ;
       void SetLive (void) ;
       state GetOldState (void) ;
       state GetNewState (void) ;
       void Calc (void) ;
       void Display (void) ;
   } ;

 Cell c[maxCols][maxRows] ;

 void Cell::InitCell (int x,int y)
  {
    xCo = x ;
    yCo = y ;
    oldState = newState = dead ;
   }

 void Cell::SetLive (void)
  {
    newState = alive ;
   }

 state Cell::GetOldState (void)
  {
    return (oldState) ;
   }

 state Cell::GetNewState (void)
  {
    return (newState) ;
   }

 void Cell::Calc (void)
  {
    int neighbors = c[xCo-1][yCo-1].GetOldState () +
                    c[xCo  ][yCo-1].GetOldState () +
                    c[xCo+1][yCo-1].GetOldState () +
                    c[xCo-1][yCo  ].GetOldState () +
                    c[xCo+1][yCo  ].GetOldState () +
                    c[xCo-1][yCo+1].GetOldState () +
                    c[xCo  ][yCo+1].GetOldState () +
                    c[xCo+1][yCo+1].GetOldState () ;
    newState = dead ;
    if ( oldState == alive && ( neighbors == 2 || neighbors == 3 ) )
      newState = alive ;
    else
      if ( oldState == dead && neighbors == 3 )
        newState = alive ;
   }

 void Cell::Display (void)
  {
    unsigned char ch ;
    oldState = newState ;
    if ( !( yCo % 2 ) )
     {
       int tophalf = newState ;
       int bothalf = c[xCo][yCo+1].GetNewState () ;
       if ( tophalf || bothalf )
        {
          if ( tophalf )
            ch = ( bothalf ) ? both : top ;
          else
            ch = bot ;
          gotoxy (yCo/2,xCo) ;
          putch (ch) ;
         }
      }
   }

 void main ()
  {
    int x , y ;
    clrscr () ;
    for ( x = 0 ; x < maxCols ; x++ )
      for ( y = 0 ; y < maxRows ; y++ )
        c[x][y].InitCell (x,y) ;
    c[39][12].SetLive () ;
    c[40][12].SetLive () ;
    c[41][12].SetLive () ;
    c[39][13].SetLive () ;
    c[41][13].SetLive () ;
    c[39][14].SetLive () ;
    c[41][14].SetLive () ;
    for ( x = 0 ; x < maxCols ; x++ )
      for ( y = 0 ; y < maxRows ; y++ )
        c[x][y].Display () ;
    getch () ;
    while ( !kbhit () )
     {
       for ( x = 1 ; x < maxCols - 1 ; x++ )
         for ( y = 1 ; y < maxRows - 1 ; y++ )
           c[x][y].Calc () ;
       clrscr () ;
       for ( x = 0 ; x < maxCols ; x++ )
         for ( y = 0 ; y < maxRows ; y++ )
           c[x][y].Display () ;
      }
   }
